package executor.impl;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

@SuppressWarnings("serial")
public class PausableQueue extends ArrayBlockingQueue<Runnable> {
	private AtomicBoolean isPaused;
	private Object lock;
	
	public PausableQueue(int capacity) {
		super(capacity);
		lock = new Object();
		isPaused = new AtomicBoolean(false);
	}
	
	public void pause() {
		isPaused.set(true);
	}
	
	public void resume() {
		isPaused.set(false);
		lock.notifyAll();
	}
	
	@Override
	public boolean offer(Runnable r) {
		if (isPaused.get())
			try {
				lock.wait();
			} catch (InterruptedException e) {}
		return super.offer(r);
	}
	
	@Override
	public boolean offer(Runnable e, long timeout, TimeUnit unit)
			throws InterruptedException {
		if (isPaused.get())
			try {
				lock.wait(unit.toMillis(timeout));
			} catch (InterruptedException ex) {}
		return super.offer(e, timeout, unit);
	}
	
	@Override
	public void put(Runnable e) throws InterruptedException {
		if (isPaused.get())
			try {
				lock.wait();
			} catch (InterruptedException ex) {}
		super.put(e);
	}
}